package com.luom.fsp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luom.fsp.annotation.AuthCheck;
import com.luom.fsp.common.BaseResponse;
import com.luom.fsp.common.DeleteRequest;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.common.ResultUtils;
import com.luom.fsp.constant.UserConstant;
import com.luom.fsp.exception.BusinessException;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.model.dto.userCoupon.UserCouponAddRequest;
import com.luom.fsp.model.dto.userCoupon.UserCouponQueryRequest;
import com.luom.fsp.model.dto.userCoupon.UserCouponUpdateRequest;
import com.luom.fsp.model.entity.UserCoupon;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.CouponVO;
import com.luom.fsp.model.vo.UserCouponVO;
import com.luom.fsp.service.UserCouponService;
import com.luom.fsp.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * 用户-优惠券关联表接口
 *
*/
@RestController
@RequestMapping("/userCoupon")
@Slf4j
public class UserCouponController {

    @Resource
    private UserCouponService userCouponService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 新增用户-优惠券关联表
     *
     * @param userCouponAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserCoupon(@RequestBody UserCouponAddRequest userCouponAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userCouponAddRequest == null, ErrorCode.PARAMS_ERROR);
        UserCoupon userCoupon = new UserCoupon();
        BeanUtils.copyProperties(userCouponAddRequest, userCoupon);
        if (userCouponAddRequest.getUserId() == null){
            User user = userService.getLoginUser(request);
            userCoupon.setUserId(user.getId());
        }
        long newUserCouponId = userCouponService.addUserCoupon(userCoupon, request);
        return ResultUtils.success(newUserCouponId);
    }

    /**
     * 删除用户-优惠券关联表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserCoupon(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserCoupon oldUserCoupon = userCouponService.getById(id);
        ThrowUtils.throwIf(oldUserCoupon == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserCoupon.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userCouponService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新用户-优惠券关联表（仅管理员可用）
     *
     * @param userCouponUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserCoupon(@RequestBody UserCouponUpdateRequest userCouponUpdateRequest) {
        if (userCouponUpdateRequest == null || userCouponUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserCoupon userCoupon = new UserCoupon();
        BeanUtils.copyProperties(userCouponUpdateRequest, userCoupon);
        // 数据校验
        userCouponService.validUserCoupon(userCoupon, false);
        // 判断是否存在
        long id = userCouponUpdateRequest.getId();
        UserCoupon oldUserCoupon = userCouponService.getById(id);
        ThrowUtils.throwIf(oldUserCoupon == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = userCouponService.updateById(userCoupon);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户-优惠券关联表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserCouponVO> getUserCouponVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        UserCoupon userCoupon = userCouponService.getById(id);
        ThrowUtils.throwIf(userCoupon == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(userCouponService.getUserCouponVO(userCoupon, request));
    }

    /**
     * 分页获取用户-优惠券关联表列表
     *
     * @param userCouponQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserCouponVO>> listUserCouponByPage(@RequestBody UserCouponQueryRequest userCouponQueryRequest) {
        long current = userCouponQueryRequest.getCurrent();
        long size = userCouponQueryRequest.getPageSize();
        // 查询数据库
        Page<UserCoupon> userCouponPage = userCouponService.page(new Page<>(current, size),
                userCouponService.getQueryWrapper(userCouponQueryRequest));
        return ResultUtils.success(userCouponService.getUserCouponVOPage(userCouponPage, null));
    }

    /**
     * 分页获取当前登录用户创建的用户-优惠券关联表列表
     *
     * @param userCouponQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserCouponVO>> listMyUserCouponVOByPage(@RequestBody UserCouponQueryRequest userCouponQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(userCouponQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userCouponQueryRequest.setUserId(loginUser.getId());
        long current = userCouponQueryRequest.getCurrent();
        long size = userCouponQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserCoupon> userCouponPage = userCouponService.page(new Page<>(current, size),
                userCouponService.getQueryWrapper(userCouponQueryRequest));
        // 获取封装类
        return ResultUtils.success(userCouponService.getUserCouponVOPage(userCouponPage, request));
    }

    /**
     * 用户当前订单可用优惠券
     */
    @GetMapping("/my/canUser")
    public BaseResponse<List<CouponVO>> listOrderCanUseCoupon(@RequestParam BigDecimal money,
                                                                     HttpServletRequest request) {
        List<CouponVO> couponVOList=userCouponService.listUserCouponVOByPage(money, request);
        // 获取封装类
        return ResultUtils.success(couponVOList);
    }

    // endregion
}
